package com.bianmaba.oauth.configuration;

import com.bianmaba.oauth.controller.OrderController;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启全局函法安全注解配置（可以函数上使用类似 @PreAuthorize("#oauth2.hasAnyScope('write','all')")）
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    private static final String ORDER_RESOURCE_ID = "order";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(ORDER_RESOURCE_ID).stateless(true);
    }

    /**
     * scope配置可以在对应的方法上注解
     *
     * @see OrderController#update()
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers("/order/**");
        http.authorizeRequests().antMatchers("/order/query").access("#oauth2.hasAnyScope('read','all')");
        http.authorizeRequests().antMatchers("/order/save").access("#oauth2.hasAnyScope('write','all')");

        http.authorizeRequests().anyRequest().authenticated();
    }
}
